#include <iostream>
#include <mysql/mysql.h>
#define HOST "localhost" // 或#define HOST "120.0.0.1"
#define USER "root"
#define PASSWORD "XyK@71986582"
#define DB "conn"
#define PORT 3306
int main()
{
    // 创建MySQL句柄
    MYSQL *mysql = mysql_init(nullptr);
    // 连接数据库
    mysql = mysql_real_connect(mysql, HOST, USER, PASSWORD, DB, PORT, nullptr, 0);
    if (mysql == nullptr)
    {
        std::cout << "mysql_real_connect fail" << std::endl;
        return 1;
    }
    // 设置客户端字符集，与mysqld保持一致。
    int n = mysql_set_character_set(mysql, "utf8");
    if (n != 0)
    {
        std::cout << "mysql_setcharacter_set fail" << std::endl;
        return 1;
    }
    // 选择要操作的数据库
    // 在做连接时已经选好了现在就不用选，只是考虑到中途需要换其他库的情况。
    // n = mysql_select_db(mysql,"conn");

    // 准备工作做好了，接下来操作库：
    // 执行SQL语句
    std::string insert1 = "insert into stu values(null,'张三',18,187562354)";
    std::string insert2 = "insert into stu values(null,'李四',18,187562154)";
    std::string delete1 = "delete from stu where id=1";
    std::string update = "update stu set name='王五' where name = '李四'";

    std::string sel = "select * from stu";
    n = mysql_query(mysql, sel.c_str());
    if (n != 0)
    {
        std::cout << "mysql_query fail" << std::endl;
        return 1;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        std::cout << "mysql_store_result fail" << std::endl;
        return 1;
    }
    int row = mysql_num_rows(res);
    int col = mysql_num_fields(res);
    for (int i = 0; i < row; i++)
    {
        MYSQL_ROW r = mysql_fetch_row(res);
        for (int j = 0; j < col; j++)
        {
            std::cout << r[j] << '\t';
        }
        std::cout << std::endl;
    }
    mysql_free_result(res);
    mysql_close(mysql);
    return 0;
}